package org.tinygroup.springmvc.handler.impl;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationUtils;
import org.tinygroup.springmvc.handler.Form;
import org.tinygroup.springmvc.handler.MethodInvokePreHandler;
import org.tinygroup.springmvc.handler.MethodInvokePreHandlerChain;
import org.tinygroup.weblayer.webcontext.form.FormCheckStrategy;

/**
 * 表单重复提交和CSRF检查
 * 
 * @author renhui
 */
public class FormRepeatAndCsrfCheckMethodInvokePreHandler implements
        MethodInvokePreHandler,Ordered {

    private FormCheckStrategy formCheckStrategy;

    public FormCheckStrategy getFormCheckStrategy() {
        return formCheckStrategy;
    }

    public void setFormCheckStrategy(FormCheckStrategy formCheckStrategy) {
        this.formCheckStrategy = formCheckStrategy;
    }

    public void doPreMethodInvokeHandler(HttpServletRequest request,
            HttpServletResponse response, Method handlerMethod, Object handler,
            MethodInvokePreHandlerChain handlerChain) {
        
        Form form = AnnotationUtils.findAnnotation(handlerMethod, Form.class);
        // 重复提交检测
        if (form != null && formCheckStrategy != null
                && (form.isCsrfCheck() || form.isRepeatCheck())) {
            formCheckStrategy.apply(request, form.isModifiedCheck());
            
            if (!(form.isRepeatCheck())) {
                request.setAttribute(
                    org.tinygroup.weblayer.webcontext.form.Form.FORM_FORBID_DUP_SUBMIT, "no");
            }
        }
        handlerChain.doPreMethodInvokeHandler(request, response, handlerMethod,
                handler);
    }


    /** 
     * @see org.springframework.core.Ordered#getOrder()
     */
    public int getOrder() {
        return 200;
    }
}